import { createStore } from 'vuex'
import dbService from '../services/indexedDB.js'

export default createStore({
  state: {
    websites: [],
    categories: [],
    currentTheme: 'light',
    isAdmin: false,
    adminPassword: 'admin123' // 简单的默认密码
  },
  mutations: {
    SET_WEBSITES(state, websites) {
      state.websites = websites;
    },
    ADD_WEBSITE(state, website) {
      state.websites.push(website);
    },
    UPDATE_WEBSITE(state, updatedWebsite) {
      const index = state.websites.findIndex(w => w.id === updatedWebsite.id);
      if (index !== -1) {
        state.websites.splice(index, 1, updatedWebsite);
      }
    },
    DELETE_WEBSITE(state, websiteId) {
      state.websites = state.websites.filter(w => w.id !== websiteId);
    },
    SET_CATEGORIES(state, categories) {
      state.categories = categories;
    },
    SET_THEME(state, theme) {
      state.currentTheme = theme;
    },
    SET_ADMIN_STATUS(state, status) {
      state.isAdmin = status;
    }
  },
  actions: {
    async initializeStore({ commit }) {
      try {
        // 初始化数据库
        await dbService.openDB();
        
        // 初始化示例数据
        await dbService.initializeSampleData();
        
        // 获取网站数据
        const websites = await dbService.getAllWebsites();
        commit('SET_WEBSITES', websites);
        
        // 提取所有分类
        const categories = await dbService.getCategories();
        commit('SET_CATEGORIES', categories);
      } catch (error) {
        console.error('初始化存储失败:', error);
      }
    },
    
    async addWebsite({ commit }, website) {
      try {
        // 使用统一的字段名
        const websiteToAdd = {
          id: website.id,
          name: website.name,
          description: website.description,
          category: website.category,
          url: website.url,
          createdAt: website.createdAt
        };
        
        await dbService.addWebsite(websiteToAdd);
        commit('ADD_WEBSITE', websiteToAdd);
        
        // 更新分类
        const categories = await dbService.getCategories();
        commit('SET_CATEGORIES', categories);
      } catch (error) {
        console.error('添加网站失败:', error);
        throw error;
      }
    },
    
    async updateWebsite({ commit }, website) {
      try {
        // 使用统一的字段名
        const websiteToUpdate = {
          id: website.id,
          name: website.name,
          description: website.description,
          category: website.category,
          url: website.url,
          createdAt: website.createdAt
        };
        
        await dbService.updateWebsite(websiteToUpdate);
        commit('UPDATE_WEBSITE', websiteToUpdate);
        
        // 更新分类
        const categories = await dbService.getCategories();
        commit('SET_CATEGORIES', categories);
      } catch (error) {
        console.error('更新网站失败:', error);
        throw error;
      }
    },
    
    async deleteWebsite({ commit }, websiteId) {
      try {
        await dbService.deleteWebsite(websiteId);
        commit('DELETE_WEBSITE', websiteId);
        
        // 更新分类
        const categories = await dbService.getCategories();
        commit('SET_CATEGORIES', categories);
      } catch (error) {
        console.error('删除网站失败:', error);
        throw error;
      }
    },
    
    setCategories({ commit }, categories) {
      commit('SET_CATEGORIES', categories);
    },
    
    setTheme({ commit }, theme) {
      commit('SET_THEME', theme);
    },
    
    setAdminStatus({ commit }, status) {
      commit('SET_ADMIN_STATUS', status);
    }
  },
  getters: {
    getAllWebsites: (state) => state.websites,
    getCategories: (state) => state.categories,
    getCurrentTheme: (state) => state.currentTheme,
    isAdmin: (state) => state.isAdmin,
    getWebsitesByCategory: (state) => (category) => {
      if (!category) return state.websites;
      return state.websites.filter(w => w.category === category);
    }
  }
});